﻿if (!InfoSource) var InfoSource = {};
if (!InfoSource.AppointmentReminders) InfoSource.AppointmentReminders = {};
if (!InfoSource.AppointmentReminders.EditTemplates) InfoSource.AppointmentReminders.EditTemplates = {};

InfoSource.AppointmentReminders.EditTemplates.RedactorsInitialized = 0;

/*========================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.Init = function () {
    $(".template-body").each(function (item) {
        InfoSource.AppointmentReminders.EditTemplates.MakeRedactor($(this));
    });
}

/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.InitHandlers = function () {
    $("body").on("click", "button.send-test-email-button", function () {
        InfoSource.AppointmentReminders.EditTemplates.TemplateEmail( $(this).siblings("input.send-test-email-to-input").val() ); 
    });

}

/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.MakeRedactor = function (jqEl) {
	jqEl.redactor(
                {
                	rangy: false,
                	buttons: ["save", "email", "deleteTemplate", "|", "formFields", "|", "bold", "italic", "underline", "formatting", "|", "outdent", "indent", "|", "unorderedlist", "orderedlist", "|", "alignment", "|", "link", "table", "horizontalrule"],
                	buttonsCustom: {
                		save: {
                			title: "Save",
                			callback: InfoSource.AppointmentReminders.EditTemplates.TemplateSave
                		}
                        ,
                		deleteTemplate: {
                			title: "Delete this template",
                			callback: InfoSource.AppointmentReminders.EditTemplates.TemplateDelete
                		}
                        ,
                		email: {
                			title: "Send test email",
                			callback: InfoSource.AppointmentReminders.EditTemplates.HandleEmailButton
                		}
						,
                		formFields: {
                			title: "Insert Customer Info Fields",
                			dropdown: {
                				custFullName: {
                					title: "Full Name",
                					callback: function (obj) { this.execCommand("insertHtml", "{full name}"); }
                				}
								,
                				custLastName: {
                					title: "Last Name",
                					callback: function (obj) { this.execCommand("insertHtml", "{last name}"); }
                				}
								,
                				custServiceStreetAddress: {
                					title: "Service Street Address",
                					callback: function (obj) { this.execCommand("insertHtml", "{Service Street Address}"); }
                				}
								,
                				custServiceCity: {
                					title: "Service City",
                					callback: function (obj) { this.execCommand("insertHtml", "{Service City}"); }
                				}
								,
                				custServiceState: {
                					title: "Service State",
                					callback: function (obj) { this.execCommand("insertHtml", "{Service State}"); }
                				}
								,
                				custServiceZip: {
                					title: "Service Zip",
                					callback: function (obj) { this.execCommand("insertHtml", "{Service Zip}"); }
                				}
								,
                				custMailingStreetAddress: {
                					title: "Mailing Street Address",
                					callback: function (obj) { this.execCommand("insertHtml", "{Mailing Street Address}"); }
                				}
								,
                				custMailingCity: {
                					title: "Mailing City",
                					callback: function (obj) { this.execCommand("insertHtml", "{Mailing City}"); }
                				}
								,
                				custMailingState: {
                					title: "Mailing State",
                					callback: function (obj) { this.execCommand("insertHtml", "{Mailing State}"); }
                				}
								,
                				custMailingZip: {
                					title: "Mailing Zip",
                					callback: function (obj) { this.execCommand("insertHtml", "{Mailing Zip}"); }
                				}
								,
                				custAppliance: {
                					title: "Appliance",
                					callback: function (obj) { this.execCommand("insertHtml", "{Appliance}"); }
                				}

                			}
                		}
                	},
                	toolbarExternal: $(jqEl).closest(".template-container").find(".editor-toolbar"),
                	linkAnchor: true,
                	linkEmail: true,
                	placeholder: "(template content)",
                	observeLinks: true,
                	plugins: ["fontfamily", "fontsize", "fontcolor"],
                	initCallback: function () {
                		InfoSource.AppointmentReminders.EditTemplates.RedactorsInitialized++;
                		InfoSource.AppointmentReminders.EditTemplates.CheckRedactorsInitialized();
                	}

                }
        );
}


/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.CheckRedactorsInitialized = function () {
    if (InfoSource.AppointmentReminders.EditTemplates.RedactorsInitialized == $(".template-body").length) {
        $("#appointmentRemindersEditTemplatesPage .pageLoader").remove();
    }
}

/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.TemplateSave = function (btnName, elBtn, objBtn, event) {
    var templateContainer = $(elBtn).closest(".template-container");
    templateContainer.append("<div class='generic-loading'/>");

    var data = {};
    data.templateName = templateContainer.find(".template-title-input").val();
    data.id = templateContainer.attr("templateid");
    data.templateBody = this.get();

    if (data.templateName == "" || data.templateName == "(name)") {
        alert("Title cannot be empty.");
        return false;
    }

    $.ajax({
        type: "POST",
        url: "/infosource/appointmentreminders/savetemplate",
        data: data,
        success:
            function (response) {
                var toolbar = elBtn.closest(".editor-toolbar");
                var msg = $("<div>successfully saved</div>")
                msg.css({ position: "absolute", display: "none", color: "white", fontWeight: "bold", top: "3px", right: "2px", background: "green", padding: "5px" });
                toolbar.append(msg);
                msg.show({ effect: "slide", duration: 250, "direction": "right", complete: function () { msg.delay(1000).hide({ effect: "slide", "direction": "right", duration: 250, complete: function () { msg.remove(); } }) } });
                if (response.AdditionalData.IsNew) {
                    var existingTemplatesContainer = $("#appointmentRemindersEditTemplatesPage-existingTemplatesContainer");
                    var newTemplate = $(
                        "<div class='template-container' style='display: none' templateid='" + response.AdditionalData.TemplateID + "'>" +
                            "<div class='editor-toolbar'></div>" +
                            "<span class='template-title'>Title:</span>" +
                            "<input type='text' class='template-title-input' value='" + data.templateName + "' />" +
                            "<textarea class='template-body'>" + data.templateBody + "</textarea>" +
                        "</div>"
                    );

                    existingTemplatesContainer.append(newTemplate);
                    var newTemplateBody = newTemplate.find(".template-body");
                    InfoSource.AppointmentReminders.EditTemplates.MakeRedactor(newTemplateBody);
                    newTemplate.slideDown(1000);

                    templateContainer.find(".template-title-input").val("(name)");
                    templateContainer.find(".template-body").redactor("set", "(template content)");

                }
            },
        error:
            function (response) {
                alert("error saving template");
            },
        complete:
            function (response) {
                templateContainer.find(".generic-loading").remove();
            },

        dataType: "json"
    });


}

/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.TemplateDelete = function (btnName, elBtn, objBtn, event) {
    var templateContainer = $(elBtn).closest(".template-container");
    templateContainer.append("<div class='generic-loading'/>");

    var data = {};
    data.id = templateContainer.attr("templateid");

    if (data.id == null || data.id == "") {
        return false;
    }

    var title = templateContainer.find(".template-title-input").val()

    $("<div>Are you sure you want to DELETE the template '" + title + "'?<br>Once deleted, the change CANNOT be undone.</div>").dialog({
        resizable: false,
        height: 140,
        width: 650,
        modal: true,
        title: "Are you sure you want to DELETE the template '" + title + "'?",
        buttons: {
            "Delete": function () {
                $(this).dialog("close");
                doDelete();
            },
            "Cancel": function () {
                templateContainer.find(".generic-loading").remove();
                $(this).dialog("close");
            }
        },
        close: function () { $(this).dialog("destroy"); }
    });


    var doDelete = function () {
        $.ajax({
            type: "POST",
            url: "/infosource/appointmentreminders/deletetemplate",
            data: data,
            success:
            function (response) {
                if (response.StatusCode == 1) {
                    templateContainer.slideUp("fast", function () { templateContainer.remove(); });
                }
            },
            error: function (response) {
                alert("failed to delete template");
            },
            complete:
            function (response) {
                templateContainer.find(".generic-loading").remove();
            },

            dataType: "json"
        });
    }


}

/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.HandleEmailButton = function (title, elBtn, objBtn) {

    var dlg = $("<div id='appointmentRemindersEditTemplatesPage-send-test-email-dialog'>" +
                    "<span class='send-test-email-to-label'>To:</span>" +
                    "<input class='send-test-email-to-input' type='text'/>" +
                    "<button class='send-test-email-button'>Send</button>" +
                "</div>")
        .dialog(
            {
                position: { my: "left top", at: "left bottom", of: elBtn },
                title: "Send Test Email",
                width: 550,
                show: { effect: "slide", duration: 250, "direction": "up" },
                close: function () { $(this).dialog("destroy"); }
            }
        ).data("templateContainer", elBtn.closest(".template-container"));
}

/*======================================================================================*/
InfoSource.AppointmentReminders.EditTemplates.TemplateEmail = function (to) {
    var templateContainer = $("#appointmentRemindersEditTemplatesPage-send-test-email-dialog").data("templateContainer")
    var templateBody = templateContainer.find(".template-body");
    var content = templateBody.redactor("get");

    var data = {};
    data.to = to;
    data.content = content;

    $.ajax({
        type: "POST",
        url: "/infosource/appointmentreminders/sendtestemail",
        data: data,
        success:
            function (response) {
                if (response.StatusCode == 1) {
                    alert("email successfully sent");
                }
                else {
                    alert("email failed");
                }
            },
        error: function (response) {
            alert("failed to send email");
        },
        complete:
            function (response) {

            },

        dataType: "json"
    });




    $("#appointmentRemindersEditTemplatesPage-send-test-email-dialog").dialog("close");
}

/*======================================================================================*/
$(document).ready(function () {
    InfoSource.AppointmentReminders.EditTemplates.Init();
    InfoSource.AppointmentReminders.EditTemplates.InitHandlers();
});